package org2;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

import java.lang.reflect.Array;
import java.util.Arrays;

@Aspect
@Component
public class MyAspect {

    @Before("execution(public void org2.UserServiceImpl.*(..))")
    public void beforeMethod(JoinPoint joinPoint){
        String methodName = joinPoint.getSignature().getName();
        String args = Arrays.toString(joinPoint.getArgs());
        System.out.println("[debug]前置通知，方法名:"+methodName+"，餐宿:"+args);
    }

    @After("execution(* org2.UserServiceImpl.*(..))")
    public void afterMethod(JoinPoint joinPoint){
        String methodName = joinPoint.getSignature().getName();
        System.out.println("[debug]后置通知,方法名:"+methodName);
    }

    @AfterReturning(value="execution(* org2.UserServiceImpl.*(..))",returning = "result")
    public void afterMethod(JoinPoint joinPoint,Object result){
        String methodName = joinPoint.getSignature().getName();
        System.out.println("[debug]返回通知,方法名："+methodName+",结果:"+result);
    }

    @AfterThrowing(value="execution(* org2.UserServiceImpl.*(..))",throwing = "ex")
    public Object afterThrowingMethod(JoinPoint joinPoint,Throwable ex){
        String methodName = joinPoint.getSignature().getName();
        System.out.println("[debug]异常通知,方法名："+methodName+",结果:"+ex);
        return null;
    }

    @Around("execution(* org2.UserServiceImpl.*(..))")
    public Object aroundMthod(ProceedingJoinPoint joinPoint) {
        String methodName = joinPoint.getSignature().getName();
        String args = Arrays.toString(joinPoint.getArgs());
        Object result = null;
        try {
            System.out.println("[debug]目标对象方法名:" + methodName);
            System.out.println("[debug]目标对象方法参数:" + args);
            System.out.println("[debug]环绕通知-->目标对象方法执行之前:");
            result = joinPoint.proceed();
            System.out.println("[debug]环绕通知-->目标对象方法出现异常时:");
        } catch (Throwable throwable) {
            throwable.printStackTrace();
            System.out.println("[debug]环绕通知-->目标对象方法出现问题");
        } finally {
            System.out.println("[debug]环绕通知-->目标对象方法执行完毕");
        }
        return result;
    }
}
